/**
 * 
 */
package edu.umd.clip.lm.tools;

import java.util.*;

import edu.berkeley.nlp.util.*;
import edu.umd.clip.lm.model.*;
import edu.umd.clip.lm.util.tree.BinaryTree;
/**
 * @author Denis Filimonov <den@cs.umd.edu>
 *
 */
public class FixClusterIds {
	public static class Options {
        @Option(name = "-tree", required = true, usage = "history tree XML file")
		public String tree;      
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
        OptionParser optParser = new OptionParser(Options.class);
        Options opts = (Options) optParser.parse(args, true);
        
		BinaryTree<HistoryTreePayload> root = LanguageModel.loadXMLHistoryTree(opts.tree);
		
		int lastId = 0;
		
		ArrayList<BinaryTree<HistoryTreePayload>> currentLevel = new ArrayList<BinaryTree<HistoryTreePayload>>(1);
		currentLevel.add(root);
		
		
		while(currentLevel.size() > 0) {
			ArrayList<BinaryTree<HistoryTreePayload>> nextLevel = new ArrayList<BinaryTree<HistoryTreePayload>>(currentLevel.size()*2);
			
			for(BinaryTree<HistoryTreePayload> node : currentLevel) {
				node.getPayload().clusterid = ++lastId;
				
				BinaryTree<HistoryTreePayload> left = node.getLeft();
				BinaryTree<HistoryTreePayload> right = node.getRight();
				
				if (left != null) nextLevel.add(left);
				if (right != null) nextLevel.add(right);
			}
			currentLevel = nextLevel;
		}
		
		LanguageModel.saveXMLHistoryTree(root, opts.tree);
	}

}
